<template>
  <div class="personList" :style="{ background: `url(${imgbgc})`, 'background-size': '100% 100%' }">
    <div class="contentBox">
      <div class="innerLeft">
        <div class="info">
          <img :src="'https://file.jiaoyangzhixin.com/evaluator/' + testId + '.jpg'" alt="">
          <div>
            <p>主试</p>
            <p>{{ testId }}</p>
          </div>
        </div>
        <div class="selectList">
          <div class="item">
            <p style="margin: 20px 0 10px;font-size:18px">筛查版(总数{{lowTotal}}剩余{{lowSurplus}})</p>
            <p>
              <el-progress :text-inside="true" :color="'#3ec9eb'" :define-back-color="'#fff'" :stroke-width="30" :percentage="(lowSurplus/lowTotal).toFixed(2)*100"></el-progress>
            </p>
          </div>
          <!-- <div class="item">
            <p style="margin: 20px 0 10px;font-size:18px">深度评估版(总数{{heightTotal}}剩余{{heightSurplus}})</p>
            <p>
              <el-progress :text-inside="true" :color="'#3ec9eb'" :define-back-color="'#fff'" :stroke-width="30" :percentage="(heightSurplus/heightTotal).toFixed(2)*100"></el-progress>
            </p>
          </div> -->
        </div>
      </div>
      <div class="innerBox">
        <el-page-header :icon="null" @back="goBack">
          <template #title>
            <el-icon><ArrowLeftBold /></el-icon>
            <span class="returnClass">返回</span>
          </template>
          <template #content>
            <div class="personinfo">
              <span>{{person.name}}</span>
              <span>{{person.birthday}}</span>
              <span>{{person.phone}}</span>
            </div>
          </template>
        </el-page-header>
        <div class="topBox">
          <div class="left">
          </div>
          <div class="right">
            <el-button type="primary" @click="addTestFn">新增测验</el-button>
          </div>
        </div>
        <div class="listBox">
          <el-scrollbar>
            <el-table :data="tableData" stripe style="width: 100%">
              <el-table-column label="序号" width="60" align='center'>
                <template #default="scope">
                  <span>{{scope.$index + 1}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="testTime" label="测试日期" width="180"  align='center' />
              <el-table-column prop="type" label="测试版本" width="180"  align='center'>
                <template #default="scope">
                  <span>{{scope.row.type== 0 ? '筛查版':'深度评估版'}}</span>
                </template>
              </el-table-column>
              <el-table-column label="分测验名称" align='center'>
                <template #default="scope">
                  <!-- <span>{{scope.row.whichQuestion=='1'? '双人关系测验':(scope.row.whichQuestion=='2'? '家庭或团体测验':'社会情境测验')}}</span> -->
                  <span style="display: inline-block;width: 120px;">{{ scope.row.desc }}</span>
                  <el-button style="background: #2b82e7;color: #fff;" @click="handleDetail(scope.$index, scope.row)">详情</el-button>
                </template>
              </el-table-column>
              <!-- <el-table-column prop="extra2" label="分测验对象"  align='center' /> -->
              <el-table-column label="操作" align='center' width="240">
                <template #default="scope">
                  <el-button v-show="scope.row.type=='0'" style="background: #2b82e7;color: #fff;" @click="handleDownLoad(scope.$index, scope.row)">下载报告</el-button>
                  <!-- <el-button @click="handleEdit(scope.$index, scope.row)">编辑</el-button> -->
                  <!-- <el-button @click="handleLook(scope.$index, scope.row)">查看</el-button> -->
                </template>
              </el-table-column>
            </el-table>
          </el-scrollbar>
        </div>
        <!-- <div class="pageBox">
          <el-pagination
            background
            :hide-on-single-page="true"
            layout="prev, pager, next"
            :total="total"
            prev-text="上一页"
            next-text="下一页"
            :page-size="pageSize"
            :current-page="pageNum"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div> -->
      </div>
    </div>
    <!-- 弹框展示 -->
    <el-dialog
      title=""
      v-model="dialogVisible"
      width="30%"
      :before-close="handleClose">
      <p v-for="(item,index) in dialogTable" :key="index" class="dialogP" style="">
        <span>{{ item.question }}{{ item.question == '社会情境'? '' : '：' }}</span>
        <span>{{ item.desc }}</span>
        <el-button style="background: #2b82e7;color: #fff;float: right;margin-top: 4px;" @click="handleEdit(index, item)">编辑</el-button>
      </p>
      <!-- <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
        </span>
      </template> -->
    </el-dialog>
  </div>
</template>

<script>
import { serverSeckGetFilesList, serverSeckGetFilesListByParentId, serverSeckGetBalance, serverSeckGetReport } from '@/api/home.js'
export default {
  data() {
    return {
      testId: localStorage.getItem("testId"),
      // testId: 10008,
      heightTotal: 0,
      heightSurplus: 0,
      lowTotal: 0,
      lowSurplus: 0,
      imgbgc: require('../assets/images/pbgc.jpg'),
      personType: 'adult',
      searchValue: '',
      tableData: [],
      total: 30,
      pageNum: 1,
      pageSize: 10,
      person: {
        name: sessionStorage.getItem('name'),
        birthday: sessionStorage.getItem('birthday'),
        phone: sessionStorage.getItem('phone')
      },
      type: '',
      WAIMS_TOKEN: '',
      dialogTable: [],
      dialogVisible: false,
      baseInfo: {
        name: '',
        sex: '0',
        health: '0',
        birthday: '',
        race: '',
        character: '',
        phone: '',
        email: '',
        classification:'1',
        prov: '',
        city: '',
        country: '',
        address: '',
        education: '',
        occupation: '',
        WAIMS_TOKEN: '',
        pid: ''
      }
    }
  },
  mounted() {
    this.person.name = sessionStorage.getItem('name')
    this.person.birthday = sessionStorage.getItem('birthday')
    this.person.phone = sessionStorage.getItem('phone')
    if(localStorage.getItem('WAIMS_TOKEN') && localStorage.getItem('WAIMS_TOKEN') !== '') {
      this.WAIMS_TOKEN = localStorage.getItem('WAIMS_TOKEN')
      this.type = this.$route.query.type ? this.$route.query.type : ''
      this.geListFn()
      this.getBalance()
    } else {
      // 清除localStorage 跳出网站
      // 清除与登录信息相关的local storage
      localStorage.removeItem("isLogin");
      localStorage.removeItem("baseInfo");
      localStorage.removeItem("proInfo");
      localStorage.removeItem("proUserFile");
      localStorage.removeItem("generalUserInfo");
      localStorage.removeItem("testId");
      // 清除session storage
      sessionStorage.clear();
      // 删除保存在cookie里的token
      document.cookie = "WAIMS_TOKEN" + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
      if(window.location.href.indexOf('https://xn--15t241ax9eqv8a.xn--fiqs8s/psych') > -1 ) {
        window.location.href = "https://xn--15t241ax9eqv8a.xn--fiqs8s/"
      } else if (window.location.href.indexOf('https://psychological-assessment.com/psych') > -1 ) {
        // 测试环境
        window.location.href = 'https://psychological-assessment.com/'
      } else {
        // 正式环境
        window.location.href = 'https://psychometrics-home.com/'
      }
    }
    this.personType = sessionStorage.getItem('personType')
    if(this.personType == 'adult') {
      this.imgbgc = require('../assets/images/pbgc.jpg')
    } else {
      this.imgbgc = require('../assets/images/cbgc.jpg')
    }
  },
  methods: {
    // 获取例数
    getBalance() {
      serverSeckGetBalance({
        WAIMS_TOKEN: this.WAIMS_TOKEN
      }).then(res => {
        console.log(res)
        if(res.code == 200) {
          this.heightTotal = res.data.height.total
          this.heightSurplus = res.data.height.surplus
          this.lowTotal = res.data.low.total
          this.lowSurplus = res.data.low.surplus
        }
      }).catch(err => {
        console.log(err)
      })
    },
    handleClose(done) {
      done();
    },
    progressFormat(percentage) {
      console.log(percentage)
      return `已用${this.did}`
    },
    goBack() {
      this.$router.push({
        path: '/testList'
      })
    },
    addTestFn() {
      // this.$router.push({
      //   path: '/selectType',
      //   query: {
      //     type: 'haveInfo4add',
      //     formInfo: JSON.stringify(this.baseInfo)
      //   }
      // })
      if(this.lowSurplus == 0) {
        this.$message({
          message: '剩余例数不足'
        })
        return
      }
      this.$router.push({
        path: '/selection',
        query: {
          selectType: 0
        }
      })
    },
    handleDetail(index,row) {
      console.log(index,row)
      this.pid = row.id
      this.dialogVisible = true
      var query = {
        WAIMS_TOKEN: this.WAIMS_TOKEN,
        id: row.id
      }
      serverSeckGetFilesListByParentId(query).then(res => {
        if(res.code === 200) {
          this.dialogTable = res.data
        }
      }).catch(err => {
        console.log(err)
      })
    },
    handleDownLoad(index,row) {
      console.log(index,row)
      serverSeckGetReport({
        WAIMS_TOKEN: this.WAIMS_TOKEN,
        id: row.id
      }).then(res => {
        // var url = res.data
        // window.location.href = url
        // this.download(row.question + '测试报告', url)
        this.$message({
          message: '下载中，成功后自动下载，请稍候'
        })
        var content = res
        var blob = new Blob([content], {
          type: 'application/pdf'
        })
        var fileName = row.desc + '测试报告.pdf'
        // edge浏览器下载方式
        if ('msSaveOrOpenBlob' in navigator) {
          window.navigator.msSaveOrOpenBlob(blob, fileName)
          return
        }
        if ('download' in document.createElement('a')) {
          // 非IE下载
          var elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else {
          // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    download(filename, url) {
      let a = document.createElement('a');
      a.style = 'display: none'; // 创建一个隐藏的a标签
      a.download = filename;
      a.href = url;
      document.body.appendChild(a);
      a.click(); // 触发a标签的click事件
      document.body.removeChild(a);
    },
    handleEdit(index,row) {
      console.log(index,row)
      this.$router.push({
        path: row.question === '双人' ? '/wholeTest4double' : (row.question === '团体' ? '/wholeTest4Family' : '/wholeTest4Society'),
        query: {
          type: 'edit',
          recordId: row.id,
          testTime: row.testTime,
          pid: this.pid,
          question: row.question
        }
      })
      // if(row.versionFlag == false) {
      //   // 跳转旧版
      //   this.$router.push({
      //     path: row.whichQuestion === '1' ? '/doubleTextListOld' : (row.whichQuestion === '2' ? '/familyTextListOld' : '/societyTextListOld'),
      //     query: {
      //       type: 'edit',
      //       recordId: row.id,
      //       itemname: row.extra2,
      //       testTime: row.testTime,
      //       questionArr: row.result
      //     }
      //   })
      // } else {
      //   // 跳转新版
      //   this.$router.push({
      //     path: row.whichQuestion === '1' ? '/doubleTextList' : (row.whichQuestion === '2' ? '/familyTextList' : '/societyTextList'),
      //     query: {
      //       type: 'edit',
      //       recordId: row.id,
      //       itemname: row.extra2,
      //       testTime: row.testTime,
      //       questionArr: row.result
      //     }
      //   })
      // }
    },
    handleLook(index, row) {
      if(row.versionFlag == false) {
        this.$router.push({
          path: '/reportOld',
          query: {
            recordId: row.id,
            whichQuestion: row.whichQuestion,
            testTime: row.testTime,
            itemname: row.extra2,
            testedId: sessionStorage.getItem('testedId')
          }
        })
      } else {
        this.$router.push({
          path: '/report',
          query: {
            recordId: row.id,
            whichQuestion: row.whichQuestion,
            testTime: row.testTime,
            itemname: row.extra2,
            testedId: sessionStorage.getItem('testedId')
          }
        })
      }
    },
    handleCurrentChange() {
      this.geListFn();
    },
    geListFn() {
      var query = {
        WAIMS_TOKEN: this.WAIMS_TOKEN,
        testedId: sessionStorage.getItem('testedId')
      }
      serverSeckGetFilesList(query).then(res => {
        if(res.code === 200) {
          this.tableData = res.data
        }
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.personList {
  height: calc(100vh - 200px);
  background: url(../assets/images/pbgc.jpg);
  background-repeat: no-repeat;
  background-size: 100% 100%;
  padding: 100px 140px;
  .contentBox {
    display: flex;
    height: 100%;
    background-color: #2b82e7;
    box-shadow: 35px 35px 50px 0px
      rgba(0, 0, 0, 0.3);
    border-radius: 10px;
  }
  .innerLeft {
    width: 300px;
    padding: 60px 20px 0 50px;
    color: #fff;
    .info {
      display: flex;
      align-items: center;
      img {
        width: 80px;
        height: 80px;
        border-radius: 50%;
        margin-right: 20px;
      }
    }
    .selectList {
      margin-top: 40px;
      .item {
        margin-top: 20px;
      }
    }
  }
  .innerBox {
    width: calc(100% - 300px);
    height: calc(100% - 80px);
    padding: 40px 20px;
    background-color: #ffffff;
    box-shadow: 35px 35px 50px 0px
      rgba(0, 0, 0, 0.3);
    border-radius: 10px;
  }
  .personinfo {
    padding: 10px 20px;
    // background: linear-gradient(to right, #bfbfbf, #efefef);
    border-radius: 20px;
    color: #333;
    background: #eee;
    font-weight: 700;

    span {
      margin-right: 20px;
    }
  }
  .topBox {
    margin: 0px 0 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .listBox {
    height: calc(100% - 100px);
  }
  .pageBox {
    margin-top: 50px;
    display: flex;
    justify-content: center;
  }
  .dialogP {
    height: 40px;line-height: 40px;
    >span {
      font-size: 16px;
      color: #333;
    }
  }
}
</style>
<style lang="scss">
.personList {
  .el-input {
    width: 200px;
    margin-right: 20px;
  }
  .el-divider--vertical {
    border-left: 0;
  }
  .el-progress-bar__innerText {
    text-align: center;
    width: 100%;
  }
  .el-page-header__title {
    .el-icon {
      padding: 4px;
      background: #2b82e7;
      color: #fff;
      border-radius: 50%;
    }
    .returnClass {
      font-size: 16px;
      font-weight: 700;
      margin-left: 10px;
      vertical-align: text-bottom;
    }
  }
}
</style>
